package ai.zixing.mashibing.basic_class.class02;

import java.util.Stack;

public class Code05_GetMinStack {

    public static class MyStack2 {
        private Stack<Integer> stackData;
        private Stack<Integer> stackMin;

        public MyStack2() {
            stackData = new Stack<>();
            stackMin = new Stack<>();
        }

        public void push(int newNum) {
            // 如果最小栈为空，则之间插入
            if (stackMin.isEmpty()) {
                stackMin.push(newNum);
            } else if (newNum < getMin()) {
                // 入股插入值更小，则将当前值插入最小栈
                stackMin.push(newNum);
            } else {
                // 如果当前值大于最小栈栈顶元素，则再次插入栈顶元素
                int newMin = stackMin.peek();
                stackMin.push(newMin);
            }
            stackData.push(newNum);
        }

        public int pop() {
            if (stackData.isEmpty()) {
                throw new RuntimeException("the stack is empty");
            }
            stackMin.pop();
            return stackData.pop();
        }

        int getMin() {
            if (stackMin.isEmpty()) {
                throw new RuntimeException("the stack is empty");
            }
            return stackMin.peek();
        }
    }
}
